package DatabaseRemote;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

public class Authentication {
	private String url = "jdbc:mysql://127.0.0.1:3306/";
	private String dbName = "smarthouseremoteserver";
	private String driver = "com.mysql.jdbc.Driver";
	private String userName = "root";
	private String password = "t02h1844";
	private Connection conn;
	private Statement st;
	private ResultSet res;
	private PreparedStatement ps;
	private boolean printMsg = true;
	
	public Authentication(){
		connect();
	}
	
	public String authenticateUser(String userssn,String password){
		String query="SELECT user.ssn,userhouse.houseId FROM userhouse,user WHERE user.ssn='"+userssn+"' && user.ssn=userhouse.userSSN && user.password='"+password+"'; ";
		String result="sql error";
		try {
				ps = conn.prepareStatement(query);
				res = ps.executeQuery();
				res.next();
				System.out.println("sql 1");
				result="RStoLS_"+res.getInt("houseId")+"_"+res.getString("ssn")+"_";
			if (printMsg) {
				System.out.println("Update Succesful");
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.print(e);
		}
		return result;
	}
	
	private void connect() {
		if (printMsg) {
			System.out.print("Trying to connect to database . . . ");
		}
		try {
			Class.forName(driver).newInstance();
			conn = DriverManager.getConnection(url + dbName, userName, password);
			st = conn.createStatement();
			if (printMsg) {
				System.out.println("Connected!!!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void disconnect() {
		try {
			conn.close();
			st.close();
			if (printMsg) {
				System.out.println("Disconnected from database.");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public String authenticationResult(String authentication){
		ArrayList authenticationList=convertStringToArrayList(authentication);		
		return authenticateUser(authenticationList.get(1).toString(),authenticationList.get(2).toString());
	}

	private ArrayList convertStringToArrayList(String stringList) {
		ArrayList taskList = new ArrayList();
		int lastSeparator = -1;
		for (int i = 0; i < stringList.length(); i++) {
			if (stringList.charAt(i) == '_') {
				taskList.add(stringList.subSequence(lastSeparator + 1, i));
				lastSeparator = i;
			}
		}
		return taskList;
	}

	private String convertArrayListToString(ArrayList arrayList) {
		String stringList = "";
		int lastSeparator = -1;
		for (int i = 0; i < arrayList.size(); i++) {
			stringList = stringList + arrayList.get(i) + "_";
		}
		return stringList;
	}
	
}
